package com.example.commons.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
public class ImageUploadController {

//    @Value("${upload.path}")
    private String uploadPath; // 使用application.properties/yml中配置的文件上传路径

    @PostMapping("/upload")
    public ResponseEntity<String> uploadImage(@RequestBody MultipartFile file) {
        System.out.println(file);
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return new ResponseEntity<>("Please select a file to upload", HttpStatus.BAD_REQUEST);
            }

            // 获取文件名
            String fileName = file.getOriginalFilename();

            // 构建文件保存路径
            Path filePath = Paths.get(uploadPath, fileName);

            // 保存文件
            Files.copy(file.getInputStream(), filePath);

            return new ResponseEntity<>("File uploaded successfully: " + fileName, HttpStatus.OK);
        } catch (IOException e) {
            return new ResponseEntity<>("Failed to upload file: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}